import {ProfileService} from "../../service/profile";
import {padString} from "../../utils/util";
import {Coolcar} from "../../service/request";

function formatDate(millis: number) {
    const dt = new Date(+millis)
    const y = dt.getFullYear()
    const m = dt.getMonth() + 1
    const d = dt.getDate()
    return `${padString(y)}-${padString(m)}-${padString(d)}`
}

const identityStatusMap = [
    "SUBMITTED",
    "PENDING",
    "VERIFIED"
]

Page({
    /**
     * 页面的初始数据
     */
    profileRefresher: 0,
    redirectURl: '',
    data: {
        hasLicURL: '',
        genders: ['未知', '男', '女', '其他'],
        genderIndex: 0,
        birthDate: "1990-01-01",
        licNo: "",
        name: "",
        state: identityStatusMap[0]
    },
    onLoad(opt) {
        if (opt.redirect) {
            this.redirectURl = decodeURIComponent(opt.redirect)
        }
        // 获取认证
        ProfileService.getProfile().then(p => {
            this.renderProfile(p)
        })

        ProfileService.getProfilePhoto().then(p=>{
            this.setData({
                hasLicURL: p.url || ''
            })
        })
    },

    renderProfile(data: any) {
        this.setData({
            licNo: data?.identity?.lic_number || '',
            name: data.identity?.name || '',
            genderIndex: data.identity?.gender || 0,
            birthDate: formatDate(data.identity?.birth_date_millis || 0),
            state: identityStatusMap[data.identity_Status || 0]
        })
    },
     onUploadLic(){
        wx.chooseImage({
            success: (result) => {
                wx.showLoading({
                    title: "驾照上传中"
                })
                if (result.tempFilePaths.length > 0) {
                    ProfileService.createProfilePhoto().then(r=>{
                        Coolcar.uploadFile({
                            localPath: result.tempFilePaths[0],
                            url:r.upload_url
                        }).then(()=>{
                            ProfileService.getProfilePhoto().then(p=>{
                                this.setData({
                                    hasLicURL: p.url || ''
                                })
                                ProfileService.completeProfilePhoto().then((r=>{
                                    wx.hideLoading()
                                    this.setData({
                                        licNo: r.lic_number,
                                        name: r.name,
                                        genderIndex: r.gender,
                                        birthDate: formatDate(r.birth_date_millis)
                                    })
                                })).catch(()=>{
                                    wx.hideLoading()
                                    wx.showToast({
                                        title:"上传驾照失败",
                                        icon:"none",
                                        duration:2000
                                    })
                                })
                            }).catch(()=>{
                                wx.hideLoading()
                                wx.showToast({
                                    title:"上传驾照失败",
                                    icon:"none",
                                    duration:2000
                                })
                            })
                        })
                    }).catch(()=>{
                        wx.hideLoading()
                        wx.showToast({
                            title:"上传驾照失败",
                            icon:"none",
                            duration:2000
                        })
                    })
                }
            },
            complete: () => {

            }
        })
    },
    onGenderChange(e: any) {
        this.setData({
            genderIndex: e.detail.value
        })
    },

    onBirthDateChange(e: any) {
        this.setData({
            birthDate: e.detail.value
        })
    },
    onSubmit() { // 提交审查
        ProfileService.submitProfile({
            licNumber: this.data.licNo,
            name: this.data.name,
            gender: +this.data.genderIndex,
            birthDateMillis: Date.parse(this.data.birthDate)
        }).then(p => {
            console.log(p)
            this.renderProfile(p)
            this.scheduleProfileRefresher()
        })
    },
    onUnload(){
      this.clearProfileRefresher()
    },
    scheduleProfileRefresher() {
        this.profileRefresher = setInterval(() => {
            ProfileService.getProfile().then(p=>{
                this.renderProfile(p)
                if (p.identity_Status !== 1){
                    this.clearProfileRefresher()
                }

                if (p.identity_Status === 2){
                    this.onLicVerified()
                }
            })
        }, 1000)
    },
    clearProfileRefresher(){
      if (this.profileRefresher){
          clearInterval(this.profileRefresher)
      }
    },
    onReSubmit() { // 重新审查
        ProfileService.clearProfile().then(p => {
            this.renderProfile(p)
            this.setData({
                hasLicURL: "",
            })
        })
    },
    onLicVerified() {
        if (this.redirectURl) {
            wx.redirectTo({
                url: this.redirectURl
            })
        }
    }
})